<template>
  <div class="details-container flex both-100" style="overflow-x: hidden;overflow-y: auto;">
    <div class="img-wrapper content-wrapper flex pr10">
      <div class="content-item">
        <custom-title title="设备平面图"></custom-title>
        <div class="img-container" style="height: 245px;">
          <template v-if="descModel.picUrl">
            <img :src="descModel.picUrl" class="img-plane" />
          </template>
          <img v-if="descModel.markIcon && descModel.picUrl" ref="imgBlock" class="mark-icon" :src="inFilePrefix + descModel.markIcon" alt="" :style="{ position: 'absolute', top: descModel.positionY_real + 'px', left: descModel.positionX_real + 'px' }">
          <img v-else-if="!descModel.markIcon && descModel.picUrl" ref="imgBlock" class="mark-icon" :src="markIcon" alt="" :style="{ position: 'absolute', top: descModel.positionY_real + 'px', left: descModel.positionX_real + 'px' }">
          <div class="img-contaienr__footer"></div>
        </div>
      </div>
      <div class="content-item" v-if="value.deviceTypeKey !== 'encodeDevice'">
        <custom-title title="监测数据"></custom-title>
        <div class="table-container" style="height: 245px;">
          <base-table :tableModel="recordList" :tableItemConfig="recordListConfig" stripe v-loading="recordListLoading" height="350" />
          <!-- 分页 -->
          <Pagination v-show="total > 0" :total="total" :pageSizes="[recordModel.pageSize]" :page.sync="recordModel.pageNum" :limit.sync="recordModel.pageSize" small layout="total, sizes, prev, next, jumper" @change="toGetDeviceCommonDataList"></Pagination>
          <!-- 分页over -->
        </div>
      </div>
    </div>
    <div class="info-wrapper content-wrapper flex pr10">
      <div class="content-item alarm-info">
        <custom-title title="设备信息"></custom-title>
        <div class="content-item__body">
          <el-skeleton :rows="6" :loading="descLoading" :throttle="100">
            <base-descriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="descModel">
              <template slot="alaramLv" slot-scope="slotProps">
                <div class="span">
                  {{ descModel[slotProps.scope.fieIdName] }}
                  <span class="urency-tag" :class="formatUrgency(descModel.alarmUrgency)"></span>
                </div>
              </template>
              <template #deviceStatus>
                <dict-tag :options="dictMap.type.device_status" :value="descModel.deviceStatus" />
              </template>
            </base-descriptions>
          </el-skeleton>
        </div>
      </div>
      <div class="content-item" v-if="value.deviceTypeKey !== 'encodeDevice'">
        <custom-title title="数据分析"></custom-title>
        <div class="conditons">
          <custom-form :formModel="recordModel" :formItemConfig="recordFormItemConfig" />
        </div>
        <div class="container">
          <div class="echart-box" ref="runningRecordChart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDeviceData } from '@/api/system/device/management';
import { getProjectPointPic } from '@/api/projectPoints/projectImg'
import { getDeviceCommonDataList, getDeviceFactorList } from '@/api/dataMonitoring'
import { mapState } from 'vuex'

import exampleImage from '@/assets/images/legend/tongyong.png';

export default {
  name: "DeviceDetail",
  props: {
    value: {
      type: Object,
      require: true
    },
    dictMap: {
      typpe: Object,
      default: () => { },
    },
  },
  data() {
    return {
      // 默认设备图标（markIcon 为null 时候使用此图片）
      markIcon: exampleImage,
      // 设备平面图列配置
      descConfig: {
        size: 'medium',
        column: '2',
      },
      // 设备信息
      descModel: {
        deviceTypeName: '',
        deviceStatus: '',
        deviceCode: '',
        deviceName: '',
        enableStatus: '',
        installPosition: '',
        remark: ''
      },
      // 设备信息配置项
      descConfigItem: [
        {
          fieIdName: 'projectPointName',
          label: '项目点位',
          span: 2
        },
        {
          fieIdName: 'deviceModel',
          label: '设备型号',
          span: 2,
        },
        {
          fieIdName: 'deviceName',
          label: '设备名称',
          span: 2,
        },
        {
          fieIdName: 'deviceTypeName',
          label: '设备类型',
          span: 2
        },
        {
          fieIdName: 'deviceCode',
          label: '设备编号',
          span: 2,
        },
        // {
        //   fieIdName: 'enableStatus',
        //   label: '是否启用',
        //   span: 2,
        // },
        {
          fieIdName: 'installPosition',
          label: '安装位置',
          span: 2,
        },
        {
          fieIdName: 'deviceStatus',
          label: '设备状态',
          span: 2,
          slotName: "deviceStatus"
        },
        {
          fieIdName: 'remark',
          label: '备注',
          span: 2
        },
      ],
      // 详情加载状态
      descLoading: false,
      // 运行记录表单（查询条件）数据
      recordModel: {
        pageNum: 1,
        pageSize: 10,
        deviceId: '',
        // 因子列表-数组
        factorList: [],
        // 因子列表-字符串-用,分开
        factors: '',
        endTime: '',
        startTime: ''
      },
      // 设备因子总数
      total: 0,
      // 运行记录表单配置项
      recordFormItemConfig: [
        {
          label: '因子选择',
          prop: 'factorList',
          component: 'BaseCheckboxGroup',
          isButton: 'true',
          options: [],
          span: 24,
          onChange: (e) => {
            this.recordModel.factors = this.recordModel.factorList.join(',')
            this.toGetDeviceCommonDataList();
          }
        },
        // {
        //   label: "开始时间",
        //   prop: "startTime",
        //   span: 12,
        //   component: 'BaseDateTimePicker',
        //   // labelWidth: "120px",
        //   clearable: true,
        //   onChange: (e) => {
        //     consol.log(5555)
        //   },
        //   'value-format': "yyyy-MM-dd hh:mm:ss"
        // },
        // {
        //   label: '结束时间',
        //   prop: 'endTime',
        //   span: 12,
        //   component: 'BaseDateTimePicker',
        //   // labelWidth: "120px",
        //   clearable: true,
        //   'value-format': "yyyy-MM-dd hh:mm:ss"
        // },
      ],
      // 运行记录
      recordList: [],
      // 运行记录表格配置
      recordListConfig: [
        {
          prop: 'dataTime',
          label: '时间'
        },
        {
          prop: 'factorCode',
          label: '因子编码'
        },
        {
          prop: 'factorName',
          label: '因子名称'
        },
        {
          prop: 'factorValue',
          label: '因子值'
        }
      ],
      // 运行记录加载状态
      recordListLoading: false,

    };
  },
  computed: {
    ...mapState('config', ['inFilePrefix'])
  },
  watch: {
    value: {
      handler(details) {
        this.$nextTick(() => {
          this.init(details)
        })
      },
      immediate: true,
      deep: true,
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    async init(params) {

      // 运行记录-设备id
      this.recordModel.deviceId = params.deviceId

      let details = await this.getDetails(params.deviceId)
      if (details && 200 == details.code) {
        let obj = details.data
        obj.projectPointName = obj.projectPoint.projectPointName
        obj.deviceTypeName = params.deviceTypeName

        // 设备管理那边平面图的大小固定(width：720，height:400) 440/720，440：当前页的设备平面图宽度
        let rate = 440 / 720
        obj.positionX_real = +obj.positionX * rate
        obj.positionY_real = +obj.positionY * rate
        this.descModel = obj

        // 获取设备监测因子列表
        let factorRes = await getDeviceFactorList(params.deviceId)
        if (factorRes && 200 == factorRes.code) {
          let factorList = factorRes.rows.map(item => {
            return {
              label: item.factorName,
              value: item.factorCode
            }
          })
          this.recordFormItemConfig.forEach(item => {
            if ('factorList' == item.prop) {
              this.$set(item, 'options', factorList)
              if (factorList.length) {
                this.recordModel.factors = factorList[0].value
                this.recordModel.factorList = [factorList[0].value]
              }
            }
          })
        }
      }

      // 获取设备平面图
      if (params.projectPointPicId) {
        let pictrue = await getProjectPointPic(params.projectPointPicId)
        if (pictrue && 200 == pictrue.code) {
          pictrue.data && this.$set(this.descModel, 'picUrl', this.inFilePrefix + pictrue.data.picUrl)
        }
      }

      // 获取设备监测通用监测数据
      this.toGetDeviceCommonDataList();
    },
    // 根据设备id获取设备详细信息
    async getDetails(deviceId) {
      if (!deviceId) return
      return await getDeviceData(deviceId)
    },
    // 解析 details 拿到 getDeviceData 接口详情里面没有的字段值
    resolveDetails(details) {
      if (details) {
        this.descModel = { ...details }
      }
    },
    // 获取设备监测通用监测数据
    async toGetDeviceCommonDataList() {
      this.recordListLoading = true
      let monitorData = await getDeviceCommonDataList(this.recordModel)
      if (monitorData && 200 == monitorData.code) {
        let list = monitorData.rows
        this.total = monitorData.total
        this.runingChart(this.$refs.runningRecordChart, list)
        this.recordList = list
      }
      this.recordListLoading = false
    },
    /**
     * 运行记录折线图
     * @param {String} id 
     * @param {Array} data e.g. [{
        "deviceId": 2,
        "dataTime": "2024-05-06 16:37:39",
        "factorCode": "01",
        "factorName": "酒精浓度",
        "factorValue": "3.5",
        "deviceFactorId": "1780528067465420811"
      }]
     */
    runingChart(chartDom, data) {
      if (!chartDom) {
        console.log("警报：获取元素" + chartDom + "错误")
        return;
      }

      let xAxis = data.map(item => item.dataTime)

      let temp = {}
      data.forEach(item => {
        if (!temp[item.factorCode]) {
          temp[item.factorCode] = {
            name: item.factorName + `(${item.factorCode})`,
            data: []
          }
        }
        temp[item.factorCode].data.push(item)
      })

      let seriesData = []
      for (let p in temp) {
        let item = temp[p]
        if (typeof item == 'object') {
          seriesData.push({
            name: item.name,
            type: 'line',
            // stack: 'Total',
            data: item.data.map(i => i.factorValue !== "" ? (parseFloat(i.factorValue) === NaN ? '' : parseFloat(i.factorValue)) : i.factorValue)
          })
        }
      }

      let myChart = this.$echarts.getInstanceByDom(chartDom);
      if (!myChart) {
        myChart = this.$echarts.init(chartDom);
      }
      var option;

      option = {
        tooltip: {
          trigger: 'axis'
        },
        // legend: {
        //   textStyle:{
        //     color: "white"
        //   },
        //   data: arr.map(item => item.factorName)
        // },
        grid: {
          top: '5%',
          left: '3%',
          right: '10%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            color: "white",
            formatter: function (value, index) {
              let arr = value.split(' ')
              return arr[0] + '\n\n' + arr[1];
            }
          },
          axisLine: {
            lineStyle: {
              color: "white"
            }
          },
          boundaryGap: false,
          data: xAxis
        },
        yAxis: {
          axisLine: {
            show: false
          },
          axisLabel: {
            color: "white"
          },
          type: 'value'
        },
        series: seriesData
      };

      option && myChart.setOption(option, true);

    }
  },
  components: {},
}
</script>

<style lang='less' scoped>
.details-container {
  box-sizing: border-box;

  .content-wrapper {
    flex-direction: column;

    .content-item {
      height: 350px;

      .content-item__body {
        height: calc(100% - 55px);
        overflow: auto;
      }
    }
  }

  .img-wrapper {
    width: 440px;
    height: 100%;
    margin-right: 40px;
  }

  .info-wrapper {
    flex: 1;
    height: 100%;

    .content-item__body {
      padding: 0 15px;
    }

    .alarm-elevance {
      box-sizing: content-box;

      /deep/.el-radio-group {
        line-height: 32px;
      }

      .btn-wrapper {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}

.img-plane {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  display: block;
  margin: auto;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}
.mark-icon {
  width: 18.5px;
  height: 26.5px;
  z-index: 1;
  position: absolute;
  user-select: none;
}

.echart-box {
  width: 614px;
  height: 300px;
}
</style>